import { createStore, combineReducers } from "redux";

const initialState = {
    cart: [{
        product: 'bread 700g',
        quantity: 2,
        unitCost: 90
    },{
        product: 'milk 500ml',
        quantity: 1,
        unitCost: 47
    }]
}
const ADD_TO_CART = "ADD_TO_CART";

//reducer
const productReducer = function(state=[], action){
    console.log("productReducer");
    return state;
}
//参数默认值由es6支持，es5不支持，需通过argument判断
const cartReducer = function(state=initialState, action){
    console.log("cartReducer");
    switch(action.type){
        case ADD_TO_CART:{
            let ret = {
                ...state,
                cart: [...state.cart, action.payload]
            }
            //cart: [...state.cart, action.payload]：合并为对象数组
            //等价于
            //let ret = Object.assign({}, state, {cart:...})，相同的属性后面的会覆盖前面的属性
            return ret; 
        }
        default:
            return state;
    }
}

const test1Reducer = function(state={}, action){
    //console.log("test1Reducer");
    return {};
}

//当前store状态树
// const allReducers = {
//     products: productReducer,
//     shoppingCart: cartReducer
// }
const allReducers = {
    productReducer,
    cartReducer,
    test1Reducer
}
//以上两种定义当前app的store均没问题，只不过store对象的属性名不一样而已
//上的属性名即为定义的名称，下的属性名即为productReducer，cartReducer（同C#简化声明对象）

//action
function addToCart(product, quantity, unitcount){
    return {
        type: ADD_TO_CART,
        payload: {product, quantity, unitcount}
    }
}
const rootReducer = combineReducers(allReducers);

let store = createStore(rootReducer);
//debugger;
console.log("initial state:", store.getState());

//定义函数在分发action时，监听store的更改
let unsubscribe = store.subscribe(()=>console.log(store.getState()));

store.dispatch(addToCart('Coffee 500gm', 1, 250));
// store.dispatch(addToCart('Flour 1kg', 2, 110));
// store.dispatch(addToCart('Juice 2L', 1, 250));
unsubscribe();

// import React from 'react';
// import ReactDOM from 'react-dom';
// import './index.css';
// import * as serviceWorker from './serviceWorker';

// ReactDOM.render(<div>111</div>, document.getElementById('root'));

// // If you want your app to work offline and load faster, you can change
// // unregister() to register() below. Note this comes with some pitfalls.
// // Learn more about service workers: http://bit.ly/CRA-PWA
// serviceWorker.unregister();
